<template>
  <div class="see-page">
    <!-- 顶部导航 -->
    <div class="nav-bar">
      <div class="nav-content">
        <span class="nav-title">房源推荐</span>
      </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-bar">
      <el-input
        v-model="keyword"
        placeholder="搜索小区名/地铁/位置等"
        clearable
        @input="onKeywordInput"
        @keyup.enter="doSearchImmediate"
        @clear="doSearchImmediate"
      >
        <template #append>
          <el-button type="primary" @click="doSearchImmediate">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 筛选条（复用房源列表的筛选逻辑） -->
    <div class="filter-section">
      <SearchFilter 
        v-model:filterState="filterState" 
        @filter-change="handleFilterChange" 
      />
      <!-- 筛选条件重置按钮 -->
      <div v-if="isFilterActive" class="filter-reset">
        <el-button 
          size="small" 
          type="info" 
          plain 
          @click="resetAllFilters"
        >
          清除筛选
        </el-button>
      </div>
    </div>

    <!-- 视图切换按钮 -->
    <div class="view-toggle">
      <el-button-group>
        <el-button 
          :type="viewMode === 'list' ? 'primary' : 'default'"
          @click="switchViewMode('list')"
          size="small"
        >
          <el-icon><Grid /></el-icon>
          列表
        </el-button>
        <el-button 
          :type="viewMode === 'map' ? 'primary' : 'default'"
          @click="switchViewMode('map')"
          size="small"
        >
          <el-icon><Location /></el-icon>
          地图
        </el-button>
      </el-button-group>
    </div>

    <!-- 内容区 -->
    <div class="content" v-loading="loading">
      <!-- 地图视图 -->
      <div v-if="viewMode === 'map'" class="map-container">
        <MapView
          :roomList="roomList"
          :loading="loading"
          :hasMore="hasMore"
          @load-more="loadMore"
          @favorite-change="onFavoriteChange"
        />
      </div>

      <!-- 列表视图 -->
      <div v-else-if="roomList.length > 0" class="room-list-container">
        <div class="room-grid">
          <RoomCard
            v-for="room in roomList"
            :key="room.id"
            :room="room"
            :showFavorite="true"
            :initialFavorited="favoriteSet.has(String(room.id))"
            @click="handleRoomClick(room)"
            @favorite-change="onFavoriteChange"
          />
        </div>

        <div class="load-more" v-if="hasMore">
          <el-button 
            :loading="loadingMore" 
            @click="loadMore" 
            type="primary" 
            plain
            class="load-more-btn"
          >
            {{ loadingMore ? '加载中...' : '加载更多' }}
          </el-button>
        </div>

        <div class="no-more" v-else>
          <span class="no-more-text">到底了，没有更多数据了</span>
        </div>
      </div>

      <!-- 无数据时：若为搜索/筛选导致无结果，展示搜索空图；否则展示找房引导 -->
      <div v-else class="empty-wrapper">
        <div v-if="isEmptyBySearch" class="search-empty">
          <img class="search-empty-img" src="@/assets/imgs/search_null_data.png" alt="未找到相关房源" />
          <div class="search-empty-tip">未找到相关房源，试试调整关键词或筛选条件</div>
        </div>
        <template v-else>
          <div class="empty-header">
            <img class="title-icon" src="@/assets/imgs/startIcon.png" alt="icon" />
            <span class="title-text">找房</span>
          </div>
          <div class="subtitle">发现你想看的房子</div>
          <div class="illustration">
            <img src="@/assets/imgs/find_room.png" alt="找房插画" />
          </div>
          <div class="tip">暂无想看房源，试试如下找房方式</div>

          <div class="find-ways">
            <div class="way-item" @click="goToCommuteMode">
              <img class="way-icon" src="@/assets/imgs/bus.svg" alt="通勤找房" />
              <div class="way-info">
                <div class="way-title">通勤找房</div>
                <div class="way-desc">按公司通勤时长找房</div>
              </div>
            </div>
            <div class="way-item" @click="goToMapMode">
              <img class="way-icon" src="@/assets/imgs/map.svg" alt="地图找房" />
              <div class="way-info">
                <div class="way-title">地图找房</div>
                <div class="way-desc">在你想住的地方找房</div>
              </div>
            </div>
          </div>
        </template>
      </div>
      <!-- 无限滚动触发器 -->
      <div ref="infiniteSentinel" class="infinite-sentinel"></div>
    </div>
  </div>
  
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Grid, Location } from '@element-plus/icons-vue'
import SearchFilter from '@/views/RoomList/components/SearchFilter.vue'
import RoomCard from '@/views/RoomList/components/RoomCard.vue'
import MapView from './components/MapView.vue'
import SimpleMapTest from '@/components/SimpleMapTest.vue'
import { getRentRoomListApi } from '@/api/room'
import { getFavorites, addFavorite, removeFavorite, isFavorited } from '@/api/favorite'

// 页面状态
const loading = ref(false)
const loadingMore = ref(false)
const roomList = ref([])
const hasMore = ref(true)
const keyword = ref('')
const favoriteSet = ref(new Set())
const viewMode = ref('list') // 'list' 或 'map'

// 分页
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})

// 是否为"搜索/筛选导致的空结果"
const isFilterActive = computed(() => {
  return !!(keyword.value && keyword.value.trim()) ||
    (Array.isArray(filterState.location) && filterState.location.length) ||
    !!filterState.rentRange || !!filterState.sortBy
})
const isEmptyBySearch = computed(() => roomList.value.length === 0 && isFilterActive.value)

// 筛选条件（与房源列表保持一致，便于后续扩展）
const filterState = reactive({
  location: '',
  rentRange: '',
  sortBy: ''
})

const searchParams = reactive({
  page: 1,
  limit: 10
})

const fetchList = async (isLoadMore = false) => {
  try {
    if (isLoadMore) {
      loadingMore.value = true
    } else {
      loading.value = true
      pagination.page = 1
      roomList.value = []
    }

    const params = {
      ...searchParams,
      page: pagination.page,
      limit: pagination.limit
    }

    // 添加关键词搜索
    if (keyword.value && keyword.value.trim()) {
      params.keyword = keyword.value.trim()
    }

    // 处理位置筛选
    if (filterState.location) {
      if (Array.isArray(filterState.location) && filterState.location.length) {
        const [provinceId, cityId, districtId] = filterState.location
        if (provinceId) params.provinceId = provinceId
        if (cityId) params.cityId = cityId
        if (districtId) params.districtId = districtId
      } else if (typeof filterState.location === 'string') {
        params.cityId = filterState.location
      }
    }

    // 处理租金范围筛选
    if (filterState.rentRange) {
      const [minRent, maxRent] = filterState.rentRange.split('-')
      if (minRent) params.minRent = minRent
      if (maxRent) params.maxRent = maxRent
    }

    // 处理排序筛选
    if (filterState.sortBy) {
      const [orderBy, orderType] = filterState.sortBy.split('-')
      if (orderBy) params.orderBy = orderBy
      if (orderType) params.orderType = orderType
    }

    // 调试日志（生产环境可移除）
    if (process.env.NODE_ENV === 'development') {
      console.log('筛选条件:', filterState)
      console.log('请求参数:', params)
    }

    const res = await getRentRoomListApi(params)
    
    // 调试日志（生产环境可移除）
    if (process.env.NODE_ENV === 'development') {
      console.log('API响应数据:', res)
    }
    
    if (isLoadMore) {
      roomList.value.push(...res.data.records)
    } else {
      roomList.value = res.data.records
    }
    pagination.total = res.data.total
    hasMore.value = roomList.value.length < res.data.total

    // const data = await getRoomRecommendListApi()
    
    // // 转换数据格式以适配现有组件
    // roomList.value = data.data.map(item => ({
    //   id: item.id,
    //   title: item.houseTitle,
    //   location: item.address,
    //   price: item.rentPriceListing,
    //   area: item.rentArea,
    //   image: item.housePicture,
    //   tag: item.tags && item.tags.length > 0 ? item.tags[0].name : '整租'
    // }))
    // 重新同步收藏集，确保卡片初始勾选正确
    syncFavoriteSet()
  } catch (e) {
    console.error(e)
    ElMessage.error('获取房源列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    pagination.page++
    fetchList(true)
  }
}

// 防抖
let debounceTimer = null
const doSearchImmediate = () => {
  updateRouteQuery()
  fetchList()
}
const onKeywordInput = () => {
  if (debounceTimer) clearTimeout(debounceTimer)
  debounceTimer = setTimeout(() => {
    updateRouteQuery()
    fetchList()
  }, 400)
}

const handleFilterChange = (newFilterState) => {
  // 更新筛选状态
  Object.assign(filterState, newFilterState)
  
  // 调试日志（生产环境可移除）
  if (process.env.NODE_ENV === 'development') {
    console.log('筛选条件已更新:', filterState)
  }
  
  updateRouteQuery()
  fetchList()
}

const router = useRouter()
const route = useRoute()
const handleRoomClick = (room) => {
  // 跳转到租房详情
  router.push({ name: 'RentRoomDetail', params: { id: room.id } })
}

// 视图模式切换
const switchViewMode = (mode) => {
  viewMode.value = mode
  // 保存到本地存储
  localStorage.setItem('see-view-mode', mode)
}

// 空状态 CTA 跳转
const goToCommuteMode = () => {
  router.push({ name: 'RoomList', query: { mode: 'commute' } })
}
const goToMapMode = () => {
  router.push({ name: 'RoomList', query: { mode: 'map' } })
}

// 重置所有筛选条件
const resetAllFilters = () => {
  filterState.location = ''
  filterState.rentRange = ''
  filterState.sortBy = ''
  keyword.value = ''
  updateRouteQuery()
  fetchList()
}

// 路由查询持久化与回显
const updateRouteQuery = () => {
  const query = {
    keyword: keyword.value || undefined,
    location: Array.isArray(filterState.location) && filterState.location.length ? filterState.location.join(',') : undefined,
    rentRange: filterState.rentRange || undefined,
    sortBy: filterState.sortBy || undefined,
    page: String(pagination.page)
  }
  router.replace({ name: 'See', query })
}

const applyRouteQuery = () => {
  const q = route.query
  keyword.value = (q.keyword && String(q.keyword)) || ''
  filterState.rentRange = (q.rentRange && String(q.rentRange)) || ''
  filterState.sortBy = (q.sortBy && String(q.sortBy)) || ''
  if (q.location) {
    const arr = String(q.location).split(',').filter(Boolean)
    filterState.location = arr
  } else {
    filterState.location = ''
  }
  // 调试日志（生产环境可移除）
  if (process.env.NODE_ENV === 'development') {
    console.log('从路由恢复筛选条件:', filterState)
  }
}

// 无限滚动
const infiniteSentinel = ref(null)
let io = null
const initInfiniteScroll = () => {
  if (!infiniteSentinel.value) return
  io = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        loadMore()
      }
    })
  }, { root: null, rootMargin: '0px', threshold: 0.1 })
  io.observe(infiniteSentinel.value)
}

onMounted(() => {
  applyRouteQuery()
  // 恢复视图模式
  const savedViewMode = localStorage.getItem('see-view-mode')
  if (savedViewMode && ['list', 'map'].includes(savedViewMode)) {
    viewMode.value = savedViewMode
  }
  // 初始拉取，若返回空则展示找房方式引导
  fetchList()
  initInfiniteScroll()
  // 初始化收藏集
  syncFavoriteSet()
})

onBeforeUnmount(() => {
  if (io && infiniteSentinel.value) io.unobserve(infiniteSentinel.value)
  if (io) io.disconnect()
  if (debounceTimer) clearTimeout(debounceTimer)
})

// 收藏：读取与更新
const syncFavoriteSet = async () => {
  try {
    const favorites = await getFavorites()
    favoriteSet.value = new Set(favorites.map(item => String(item.id)))
  } catch (error) {
    console.error('同步收藏状态失败:', error)
  }
}

const onFavoriteChange = async ({ id, favorited }) => {
  try {
    if (favorited) {
      await addFavorite(id)
      favoriteSet.value.add(String(id))
      ElMessage.success('已收藏')
    } else {
      await removeFavorite(id)
      favoriteSet.value.delete(String(id))
      ElMessage.success('已取消收藏')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error(favorited ? '收藏失败，请稍后重试' : '取消收藏失败，请稍后重试')
    // 恢复UI状态
    if (favorited) {
      favoriteSet.value.delete(String(id))
    } else {
      favoriteSet.value.add(String(id))
    }
  }
}
</script>

<style scoped>
.see-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #e9f8ef 0%, #f5f5f5 30%, #f5f5f5 100%);
}

.nav-bar {
  background-color: transparent;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 56px;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.content {
  position: relative;
}

/* 搜索框 */
.search-bar {
  padding: 8px 16px 0;
  background-color: transparent;
}

/* 筛选区域 */
.filter-section {
  position: relative;
}

.filter-reset {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
}

/* 视图切换 */
.view-toggle {
  padding: 8px 16px;
  background-color: transparent;
  display: flex;
  justify-content: center;
}

.map-container {
  height: calc(100vh - 200px);
  min-height: 500px;
}

/* 空状态 */
.empty-wrapper {
  padding: 12px 16px 24px;
}

.empty-header {
  display: flex;
  align-items: center;
  gap: 6px;
}

.title-icon {
  width: 20px;
  height: 20px;
}

.title-text {
  font-size: 22px;
  font-weight: 700;
}

.subtitle {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}

.illustration {
  margin: 16px auto 8px;
  width: 86%;
  border: 1px dashed #e4e4e4;
  border-radius: 8px;
  overflow: hidden;
}

.illustration img {
  width: 100%;
  display: block;
}

.tip {
  margin: 10px 0 14px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}

.find-ways {
  margin: 10px 16px 0;
  padding: 16px;
  border: 1px dashed #e4e4e4;
  border-radius: 8px;
  background-color: #fff;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.way-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.way-icon {
  width: 28px;
  height: 28px;
}

.way-title {
  font-weight: 700;
}

.way-desc {
  font-size: 12px;
  color: #999;
}

/* 列表 */
.room-list-container {
  padding: 16px;
}

.room-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.load-more {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.load-more-btn { min-width: 120px; }

.no-more { display: flex; justify-content: center; padding: 20px 0; }
.no-more-text { font-size: 14px; color: #999; }

.infinite-sentinel { height: 1px; }

/* 搜索空结果样式 */
.search-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 24px 16px;
}

.search-empty-img {
  width: 72%;
  max-width: 420px;
  height: auto;
  display: block;
}

.search-empty-tip {
  margin-top: 12px;
  color: #666;
  font-size: 14px;
}
</style>
